//
//  ZJExtensionAgentController.m
//  这家测试项目
//
//  Created by IOS_DEVELOPER on 2017/6/6.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJExtensionAgentController.h"
#import "ZJExtensionAgentView.h"
#import "ZJMineProjectCell.h"
#import "ZJCustomerCell.h"
#import "ZJCustomerModel.h"

#import "ZJExtensionMoneyAccountVC.h"
#import <AssetsLibrary/AssetsLibrary.h>
#define kCloseCellHeight    169.f
#define kOpenCellHeight     438.f
@interface ZJExtensionAgentController ()<UITableViewDelegate,UITableViewDataSource,ZJMineProjectCellDelegate>{
    
    UIImage *_resultImg;
    NSInteger page;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (strong, nonatomic) UISegmentedControl *segment;
@property (strong, nonatomic) ZJExtensionAgentView * extensionAgentView; //推广码
@property (strong, nonatomic) UITableView * mineCodeTableView; //项目
@property (strong, nonatomic) UITableView * projectTableView; //项目
@property (strong, nonatomic) UITableView * customerTableView; //客户
@property (nonatomic, strong) NSMutableArray<NSNumber *> *cellHeights;
@property (strong, nonatomic) UIView * qrView;
@property (strong, nonatomic) NSArray * modelArr;
@property (strong, nonatomic) UIView *bottomMoveView;
@end

@implementation ZJExtensionAgentController

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
#pragma mark -初始化
-(ZJExtensionAgentView *)extensionAgentView{
    if (!_extensionAgentView) {
        self.extensionAgentView = [[[NSBundle mainBundle] loadNibNamed:@"ZJExtensionAgentView" owner:self options:nil] lastObject];

    }
    return _extensionAgentView;
}
-(UITableView *)projectTableView{
    if (!_projectTableView) {
        _projectTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _projectTableView.frame = CGRectMake(self.scrollView.frame.size.width, 0, SCREEN_WIDTH, self.scrollView.frame.size.height+30);
        [_projectTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZJMineProjectCell class]) bundle:nil] forCellReuseIdentifier:@"ZJMineProjectCell"];
        _projectTableView.delegate = self;
        _projectTableView.dataSource = self;
        _projectTableView.showsVerticalScrollIndicator = NO;
        _projectTableView.showsHorizontalScrollIndicator = NO;
        _projectTableView.backgroundColor = [UIColor whiteColor];
//        self.projectTableView.rowHeight = 160;
        _projectTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _projectTableView;
}
-(UITableView *)mineCodeTableView{
    if (!_mineCodeTableView) {
        _mineCodeTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _mineCodeTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.scrollView.frame.size.height);
        [_mineCodeTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
        _mineCodeTableView.delegate = self;
        _mineCodeTableView.dataSource = self;
        _mineCodeTableView.showsVerticalScrollIndicator = NO;
        _mineCodeTableView.showsHorizontalScrollIndicator = NO;
        _mineCodeTableView.backgroundColor = [UIColor whiteColor];
        //        self.projectTableView.rowHeight = 160;
        _mineCodeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _mineCodeTableView;
}
-(UITableView *)customerTableView{
    if (!_customerTableView) {
        _customerTableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _customerTableView.frame = CGRectMake(self.scrollView.frame.size.width*2, 0, SCREEN_WIDTH, self.scrollView.frame.size.height - 60);
        [_customerTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZJCustomerCell class]) bundle:nil] forCellReuseIdentifier:@"ZJCustomerCell"];
        _customerTableView.delegate = self;
        _customerTableView.dataSource = self;
        _customerTableView.showsVerticalScrollIndicator = NO;
        _customerTableView.showsHorizontalScrollIndicator = NO;
        _customerTableView.rowHeight = 80;
        _customerTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_customerTableView setSeparatorColor:[Utils colorWithHexString:@"dddddd"]];
    }
    return _customerTableView;
}
- (NSMutableArray<NSNumber *> *)cellHeights
{
    if (!_cellHeights) {
        _cellHeights = [NSMutableArray array];
    }
    return _cellHeights;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton* backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setImage:[UIImage imageNamed:@"nav_icon_fh"]
                forState:UIControlStateNormal];
    [backButton sizeToFit];
    [backButton addTarget:self
                   action:@selector(backAction)
         forControlEvents:UIControlEventTouchUpInside];
    
    backButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    self.headView.backgroundColor = [Utils colorWithHexString:allConstHexColor];
    self.navigationItem.leftBarButtonItem =
    [[UIBarButtonItem alloc] initWithCustomView:backButton];
    page = 1;
    [self setupSegment];
    [self setupScrollView];
    [self createCellHeightsArray];
    
    [self sendRequest];
}
-(void)backAction{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)sendRequest{

//    [HUD showLoading:@"加载数据中..."];
    NSDictionary *parameter = [LRNetwork requestParameter:@{@"p":@(page)}];
    NSString *url = [LRNetwork requestURL:@"cgi/customer.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        
        self.modelArr = [ZJCustomerModel mj_objectArrayWithKeyValuesArray:returnValue[@"customer"]];
        [HUD hide];
        [self.customerTableView reloadData];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        
    }];
}
- (void)createCellHeightsArray
{
    for (int i = 0; i < 5; i ++) {
        [self.cellHeights addObject:@(kCloseCellHeight)];
    }
}
-(void)setupSegment{
    //先生成存放标题的数据
    NSArray *array = [NSArray arrayWithObjects:@"我的推广码",@"我的项目",@"我的客户", nil];
    //初始化UISegmentedControl
    self.segment = [[UISegmentedControl alloc]initWithItems:array];
    //设置frame
    self.segment.frame = CGRectMake(0, self.headView.height - 52, SCREEN_WIDTH, 50);
    //根据内容定分段宽度
    self.segment.apportionsSegmentWidthsByContent = YES;
    //开始时默认选中下标(第一个下标默认是0)
    self.segment.selectedSegmentIndex = 0;
    //控件渲染色(也就是外观字体颜色)
    self.segment.tintColor = [UIColor clearColor];
    
    // 正常状态下
    NSDictionary * normalTextAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:[Utils iphone5AutoScaleW:14.0]],NSForegroundColorAttributeName : [UIColor colorWithRed:247.0/255.0 green:247.0/255.0 blue:247.0/255.0 alpha:0.5]};
    [self.segment setTitleTextAttributes:normalTextAttributes forState:UIControlStateNormal];
    
    // 选中状态下
    NSDictionary * selctedTextAttributes = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:[Utils iphone5AutoScaleW:14.0]],NSForegroundColorAttributeName : [UIColor whiteColor]};
    [self.segment setTitleTextAttributes:selctedTextAttributes forState:UIControlStateSelected];
    [self.segment setContentOffset:CGSizeMake(-11,0) forSegmentAtIndex:0];
    [self.segment setContentOffset:CGSizeMake(-11,0) forSegmentAtIndex:1];
    [self.segment setContentOffset:CGSizeMake(-11,0) forSegmentAtIndex:2];

    //添加事件
    [self.segment addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
    
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, self.segment.y + self.segment.height, SCREEN_WIDTH/3, 2)];
    view.backgroundColor = RGB(237, 236, 236);
    [self.view addSubview:view];
    view.layer.shadowColor = RGB(235, 235, 235).CGColor;;
    view.layer.shadowOpacity = 0.8f;
    view.layer.shadowOffset = CGSizeMake(0,0.1);
    self.bottomMoveView = view;
    //添加到视图
    [self.view addSubview:self.segment];
}
-(void)change:(UISegmentedControl *)sender{

    if (sender.selectedSegmentIndex == 0) {
         [self.bottomMoveView.layer addAnimation:[self moveX:0.5f X:[NSNumber numberWithFloat:0.0f]] forKey:nil];
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];

    }else if (sender.selectedSegmentIndex == 1){
         [self.bottomMoveView.layer addAnimation:[self moveX:0.5f X:[NSNumber numberWithFloat:self.bottomMoveView.width]] forKey:nil];
         [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width, 0) animated:YES];
        
    }else if (sender.selectedSegmentIndex == 2){
       [self.bottomMoveView.layer addAnimation:[self moveX:0.5f X:[NSNumber numberWithFloat:self.bottomMoveView.width* 2]] forKey:nil];
         [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width*2, 0) animated:YES];
    }
}
-(void)setupScrollView{
    self.scrollView.bounces = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*3, 0);
    self.scrollView.frame = CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT-180);
    //添加页面
    self.extensionAgentView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.scrollView.frame.size.height);

    [self.scrollView addSubview:self.extensionAgentView];
    
    UIButton * jumpShouYi = [[UIButton alloc]initWithFrame:CGRectMake(self.scrollView.width * 2, self.scrollView.height - 20, self.scrollView.width, 50)];
    [jumpShouYi setBackgroundColor:[Utils colorWithHexString:allConstHexColor]];
    [jumpShouYi setTitle:@"收益详情" forState:0];
    jumpShouYi.titleLabel.font = [UIFont systemFontOfSize:[Utils iphone5AutoScaleW:14.0f]];
    [jumpShouYi addTarget:self action:@selector(jumpShouYi) forControlEvents:UIControlEventTouchUpInside];

    WEAK_SELF
    //我的客户
    [self.customerTableView setRefreshWithHeaderBlock:^{
        STRONG_SELF
//        [HUD showSucceedMsg:@"头部刷新成功"];
        [strongSelf.customerTableView headerEndRefreshing];
        
    } footerBlock:^{
        STRONG_SELF
//        [HUD showSucceedMsg:@"尾部刷新成功"];
        [strongSelf.customerTableView footerEndRefreshing];
        
    }];
    [self.scrollView addSubview:jumpShouYi];
    [self.scrollView addSubview:self.projectTableView];
    [self.scrollView addSubview:self.customerTableView];
    [self.scrollView addSubview:self.mineCodeTableView];
}
- (IBAction)QRCodeBtn:(UIButton *)sender {
    
    HMScannerController *scanner = [HMScannerController scannerWithCardName:@"" avatar:nil completion:^(NSString *stringValue) {
        
        NSArray *arr = [stringValue componentsSeparatedByString:@"="];
        if (arr.count < 2) {
            return;
        }
        [HUD showMsg:@"扫描结束"];
        
    }];
    
    [scanner setTitleColor:[UIColor whiteColor] tintColor:GREEN_COLOR];
    
    [self showDetailViewController:scanner sender:nil];

}
- (IBAction)backBtn:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)downQRBtn{

    /**
     *  将图片保存到本地相册
     */
    [self makeScreenShotCompletion:^(UIImage *image) {
        
    }];
}

#pragma mark - 跳转收益详情
-(void)jumpShouYi{

    ZJExtensionMoneyAccountVC *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"ZJExtensionMoneyAccountVC"];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -UITableViewDatsource代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.projectTableView) {
        return 1;
    }else if(tableView == self.customerTableView){
        [tableView tableViewDisplayWitMsg:kNoDataImgName ifNecessaryForRowCount:self.modelArr.count];
        return self.modelArr.count;
    }else if(tableView == self.mineCodeTableView){
        [tableView tableViewDisplayWitMsg:kNoDataImgName ifNecessaryForRowCount:self.modelArr.count];
        return 1;
    }else{
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.projectTableView) {
        ZJMineProjectCell *projectCell = [tableView dequeueReusableCellWithIdentifier:@"ZJMineProjectCell" forIndexPath:indexPath];
        projectCell.delegate = self;
        projectCell.tag = indexPath.row;
        ZJProjectDetailModel * model = GET_PROJECTINFO;
        projectCell.toptitle.text = model.share_desc;
        projectCell.codeLabel.text = self.extensionAgentView.extensionAgentCode.text;
        projectCell.qrKimg.image = [UIImage imageWithContentsOfFile:[Utils imgPath:@"tgy_pic_bg@3x.png"]];
        projectCell.titleImg.image = [UIImage imageWithContentsOfFile:[Utils imgPath:@"tgy_logo@3x.png"]];
        [projectCell.downPhotoBtn addTarget:self action:@selector(downQRBtn) forControlEvents:UIControlEventTouchUpInside];
        self.qrView = projectCell.contentView;
        projectCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return projectCell;
        
    }else if (tableView == self.customerTableView){
        ZJCustomerCell *customerCell = [tableView dequeueReusableCellWithIdentifier:@"ZJCustomerCell" forIndexPath:indexPath];
        ZJCustomerModel * model = self.modelArr[indexPath.row];
        customerCell.model = model;
        customerCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return customerCell;
        
    }else if (tableView == self.mineCodeTableView){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
        [cell.contentView addSubview:self.extensionAgentView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone; 
        return cell;
        
    }else{
        return nil;
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.projectTableView) {
        return 560;
    }else if(tableView == self.customerTableView){
        return 80;
    }else if(tableView == self.mineCodeTableView){
        return 520;
    }else return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
#pragma mark - ZJMineProjectCellDelegate
-(void)onClickRoom:(NSDictionary *)roomDict{

//    UIGraphicsBeginImageContext(self.qrView.bounds.size);
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.qrView.width, 450), NO, 0.0);//原图
    [self.qrView.layer renderInContext:UIGraphicsGetCurrentContext()];
    //获取图片
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//    UIImage *resultImg = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, 0, self.qrView.width, 470))];

    //关闭上下文
    UIGraphicsEndImageContext();

    
    _resultImg = image;
    NSArray *images = @[_resultImg];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:images applicationActivities:nil];
    //不出现在活动项目
    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            [HUD showSucceedMsg:@"分享成功"];
            //分享 成功
        } else  {
//             [HUD showErrorMsg:@"分享失败"];
            //分享 取消
        }
    };
}

#pragma mark -UIScrollView代理
/**
 *  滚动视图停下来,修改页面控件的小点（页数）
 */
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        return;
    }
    //计算页数
    int page = scrollView.contentOffset.x / scrollView.bounds.size.width;
    
    switch (page) {
        case 0:
        {
             [self.bottomMoveView.layer addAnimation:[self moveX:0.5f X:[NSNumber numberWithFloat:0.0f]] forKey:nil];
            self.segment.selectedSegmentIndex = 0;
        }
            break;
        case 1:
        {
            [self.bottomMoveView.layer addAnimation:[self moveX:0.5f X:[NSNumber numberWithFloat:self.bottomMoveView.width]] forKey:nil];
            self.segment.selectedSegmentIndex = 1;
        }
            break;
        case 2:
        {
            [self.bottomMoveView.layer addAnimation:[self moveX:0.5f X:[NSNumber numberWithFloat:self.bottomMoveView.width*2]] forKey:nil];
            self.segment.selectedSegmentIndex = 2;
        }
            break;
            
            
        default:
            break;
    }
}


-(void)makeScreenShotCompletion:(void(^)(UIImage * image))completion{
    //开启上下文  <span style="font-family: Arial, Helvetica, sans-serif;">设置截屏大小</span>
//    UIGraphicsBeginImageContext(self.qrView.bounds.size);
    [self.qrView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.qrView.width, 450), NO, 0.0);//原图
    [self.qrView.layer renderInContext:UIGraphicsGetCurrentContext()];
    //获取图片
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//    UIImage *resultImg = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, 0, self.qrView.width, 470))];
    //关闭上下文
    UIGraphicsEndImageContext();
    completion(image);
    
    _resultImg = image;
    /**
     *  将图片保存到本地相册
     */
    UIImageWriteToSavedPhotosAlbum(_resultImg, self , @selector(image:didFinishSavingWithError:contextInfo:), nil);//保存图片到照片库
    
}
// 成功保存图片到相册中, 必须调用此方法, 否则会报参数越界错误
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error) {
        NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
        [HUD showErrorMsg:@"保存失败"];
    }else{
        [HUD showSucceedMsg:@"保存成功"];
    }
}

-(CABasicAnimation *)moveX:(float)time X:(NSNumber *)x
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];///.y的话就向下移动。
    animation.toValue = x;
    animation.duration = time;
    animation.removedOnCompletion = NO;//yes的话，又返回原位置了。
//    animation.repeatCount = MAXFLOAT;
    animation.fillMode = kCAFillModeForwards;
    return animation;
}

@end
